package xyz.zhzby.cyzx.acl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import xyz.zhzby.cyzx.acl.convert.UserConvert;
import xyz.zhzby.cyzx.acl.dto.request.UserPageRequest;
import xyz.zhzby.cyzx.acl.dto.response.UserResponse;
import xyz.zhzby.cyzx.acl.entity.User;
import xyz.zhzby.cyzx.acl.mapper.UserMapper;
import xyz.zhzby.cyzx.acl.service.IUserRoleService;
import xyz.zhzby.cyzx.acl.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import xyz.zhzby.cyzx.security.util.CyzxSecurityContextHolder;
import xyz.zhzby.cyzx.servicebase.domain.DataLogInfo;
import xyz.zhzby.cyzx.servicebase.domain.PageResponse;
import xyz.zhzby.cyzx.servicebase.domain.RestResponse;
import xyz.zhzby.cyzx.servicebase.utils.MDUtil;
import xyz.zhzby.cyzx.servicebase.utils.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户类 服务实现类
 * </p>
 *
 * @author zby
 * @since 2021-12-07
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private IUserRoleService roleService;

    @Override
    public User getUserByUsername(String username) {
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        qw.eq(User::getUsername, username);
        return baseMapper.selectOne(qw);
    }

    @Override
    public RestResponse<String> saveUser(User user) {
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        qw.eq(User::getUsername, user.getUsername());
//        todo 手机号、邮箱是否限制单账号使用?  下修改同
//                .or().eq(User::getPhone, user.getPhone()).or().eq(User::getEmail, user.getEmail());
        if (baseMapper.selectOne(qw) != null) {
            return RestResponse.fail("用户名已存在");
        }
        CyzxSecurityContextHolder.getSubject().fillCreateInfo(user, DataLogInfo.USER_FIELD_ACTUAL_NAME);
        user.setPassword(MDUtil.encryption(user.getPhone()));
        baseMapper.insert(user);
        return RestResponse.success("添加成功");
    }

    @Override
    public RestResponse<PageResponse<UserResponse>> getUsers(UserPageRequest pageRequest) {
        Page<User> page = new Page<>(pageRequest.getPage(), pageRequest.getLimit());
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        if (StringUtils.isNotNullOrBlank(pageRequest.getName())) {
            String str = pageRequest.getName();
            qw.like(User::getUsername, str)
                    .or().like(User::getName, str)
                    .or().like(User::getNickName, str);
        }
        qw.orderByAsc(User::getId);
        IPage<User> userPage = baseMapper.selectPage(page, qw);
        List<User> records = userPage.getRecords();
        List<UserResponse> userResponses = UserConvert.INSTANCE.USER_RESPONSE_LIST(records);
        return RestResponse.success(new PageResponse<>(userResponses, userPage.getTotal(), pageRequest.getPage(), pageRequest.getLimit()));
    }

    @Override
    public RestResponse<String> updateUser(User user) {
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        qw.eq(User::getUsername, user.getUsername());
        User selectOne = baseMapper.selectOne(qw);
        if (selectOne != null && !selectOne.getId().equals(user.getId())) {
            return RestResponse.fail("用户名已存在");
        }
        CyzxSecurityContextHolder.getSubject().fillUpdateInfo(user, DataLogInfo.USER_FIELD_ACTUAL_NAME);
        baseMapper.updateById(user);
        return RestResponse.success("修改成功");
    }

    @Override
    public RestResponse<UserResponse> getUserById(Long userId) {
        return RestResponse.success(UserConvert.INSTANCE.USER_RESPONSE(baseMapper.selectById(userId)));
    }

    @Override
    public RestResponse<Map<String, Object>> getUserInfoById(Long userId) {
        User user = baseMapper.selectById(userId);
        Map<String, Object> res = new HashMap<>();
        res.put("id", user.getId());
        res.put("username", user.getUsername());
        res.put("nickName", user.getNickName());
        res.put("name", user.getName());
        res.put("gender", user.getGender());
        res.put("phone", user.getPhone());
        res.put("email", user.getEmail());
        res.put("avatar", user.getAvatar());
        res.put("signature", user.getSignature());
        return RestResponse.success(res);
    }

    @Override
    public List<Map<String, Object>> getUserInfoByIdList(List<Long> userIds) {
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        qw.in(User::getId, userIds);
        qw.select(User::getId, User::getNickName, User::getAvatar);
        List<User> users = baseMapper.selectList(qw);
        List<Map<String, Object>> res = new ArrayList<>();
        for (User user : users) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", user.getId());
            map.put("nickName", user.getNickName());
            map.put("avatar", user.getAvatar());
            res.add(map);
        }
        return res;
    }

    @Override
    public RestResponse<String> deleteUser(Long userId) {
        roleService.removeByUserId(userId);
        //todo 是否删除其兴趣做题记录等等？
        baseMapper.deleteById(userId);
        return RestResponse.success("删除成功");
    }

    @Override
    public RestResponse<String> deleteUserBatch(List<Long> userIds) {
        userIds.forEach(this::deleteUser);
        return RestResponse.success("删除成功");
    }
}
